<template>
  <div class="quill-editor-container">
    <quill-editor
      v-model:content="editorContent"
      content-type="html"
      theme="snow"
      :toolbar="toolbarOptions"
      @blur="handleBlur"
      @ready="onEditorReady"
      @update:content="handleContentUpdate"
    />
  </div>
</template>

<script lang="ts" setup>
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ref, watch } from 'vue'

interface Props {
  modelValue?: string
  placeholder?: string
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '',
})

const emit = defineEmits(['update:modelValue', 'blur'])

const editorContent = ref(props.modelValue)

// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote', 'code-block'],
  [{ header: 1 }, { header: 2 }],
  [{ list: 'ordered' }, { list: 'bullet' }],
  [{ script: 'sub' }, { script: 'super' }],
  [{ indent: '-1' }, { indent: '+1' }],
  [{ direction: 'rtl' }],
  [{ size: ['small', false, 'large', 'huge'] }],
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ color: [] }, { background: [] }],
  [{ font: [] }],
  [{ align: [] }],
  ['clean'],
]

// 编辑器就绪
const onEditorReady = () => {
  if (props.modelValue) {
    editorContent.value = props.modelValue
  }
}

// 内容更新
const handleContentUpdate = (content: string) => {
  if (content !== props.modelValue) {
    emit('update:modelValue', content)
  }
}

// 编辑器失焦
const handleBlur = () => {
  const content = editorContent.value || ''
  if (content !== props.modelValue) {
    emit('update:modelValue', content)
  }
  emit('blur', content)
}

// 监听外部值变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal !== editorContent.value) {
      editorContent.value = newVal
    }
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
.quill-editor-container {
  :deep(.ql-container) {
    min-height: 200px;
  }
}
</style>
